package com.lwb.eduservice.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lwb.eduservice.entity.EduSubject;
import com.lwb.eduservice.entity.excel.ExcelSubjectData;
import com.lwb.eduservice.service.EduSubjectService;
import com.lwb.serviceBase.GlobalExceptionHandler;
import com.lwb.serviceBase.StudyException;

public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    //因为SubjectExcelListener不能交给spring进行管理，需要自己new，不能注入其他对象
    //不能实现数据库操作
    public EduSubjectService eduSubjectService;
    public SubjectExcelListener() {};
    public SubjectExcelListener(EduSubjectService eduSubjectService){
        this.eduSubjectService = eduSubjectService;
    }

    //读取excel内容，一行一行进行读取
    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        if (excelSubjectData == null){
            throw new StudyException(20001,"文件数据为空");
        }

        //一行一行读取，每次读取有两个值，第一个值一级分类，第二个值二级分类
        //对于一级分类进行判断
        EduSubject oneEduSubject = existOneSubject(eduSubjectService, excelSubjectData.getOneSubjectName());
        if(oneEduSubject == null){
            oneEduSubject = new EduSubject();
            oneEduSubject.setTitle(excelSubjectData.getOneSubjectName());
            oneEduSubject.setParentId("0");
            eduSubjectService.save(oneEduSubject);
        }
        //获取一级目录的id
        String pid = oneEduSubject.getId();
        //对于二级目录进行判断
        EduSubject twoEduSubject = existTwoSubject(eduSubjectService, excelSubjectData.getTwoSubjectName(), pid);
        if(twoEduSubject == null){
            twoEduSubject = new EduSubject();
            twoEduSubject.setTitle(excelSubjectData.getTwoSubjectName());
            twoEduSubject.setParentId(pid);
            eduSubjectService.save(twoEduSubject);
        }
    }

    //判断一级分类，一级分类不能重复添加
    //name是一级分类名称
    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id","0");
        EduSubject oneSubject = eduSubjectService.getOne(queryWrapper);
        return  oneSubject;
    }

    //判断二级分类，二级分类不能重复
    //name是二级分类名称，pid是一级分类的id
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",pid);
        EduSubject twoSubject = eduSubjectService.getOne(queryWrapper);
        return  twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
